package com.zhang.spark_1.spark_core.wordCount

import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}

/**
 * @title:
 * @author: zhang
 * @date: 2021/12/4 21:04
 */
object Spark03_WordCount {
  def main(args: Array[String]): Unit = {
    //获取spark连接

    val conf: SparkConf = new SparkConf().setMaster("local").setAppName("WordCount")
    val sc: SparkContext = new SparkContext(conf)

    val value: RDD[String] = sc.textFile("datas")
    val words: RDD[String] = value.flatMap(_.split(" "))

    val wordMap: RDD[(String, Int)] = words.map((_, 1))
    val wordGroup: RDD[(String, Iterable[(String, Int)])] = wordMap.groupBy(_._1)

    wordGroup.foreach(println)
    val wordCount: RDD[(String, Int)] = wordGroup.map {
      case (word, list) => {
        list.reduce(
          (t1, t2) => {
            (t1._1, t1._2 + t2._2)
          }
        )
      }
    }
    val array: Array[(String, Int)] = wordCount.collect()
    array.foreach(println)


    //关闭资源
    sc.stop()
  }
}
